export interface ToolDefinition {
    description: string;
    schema: {
        type: string;
        properties: Record<string, any>;
        required?: string[];
    };
}

export const toolDefinitions: Record<string, ToolDefinition> = {
    "api-doc-search": {
        description: "搜索SpreadJS相关的技术文档和API信息。当你需要了解如何使用SpreadJS的特定功能API时使用此工具。",
        schema: {
            type: "object",
            properties: {
                keyword: {
                    type: "string",
                    description: "需要搜索SpreadJS如何使用的关键词"
                }
            },
            required: ["keyword"]
        }
    },

    "execute-spreadjs": {
        description: "生成SpreadJS代码来执行特定操作。使用此工具来创建、修改或查询SpreadJS表格数据。建议在使用前通过api-doc-search了解相关API信息以确保代码准确性。",
        schema: {
            type: "object",
            properties: {
                execute_logic: {
                    type: "string",
                    description: "让 SpreadJS 执行的操作代码，例如设置单元格值、应用样式等。Workbook实例已存在, 名为workbook, GC命名空间也已经存在, 这二者都可以直接调用, 不要重复定义。如果想要用sheet, 需要先生成获取sheet的代码, 然后调用sheet的API。"
                },
                query_logic: {
                    type: "string",
                    description: "执行操作后，用于查询和验证结果的代码，其结果将返回给 AI。返回的代码需要是完整的代码, 不要有任何注释。返回结果类型是数组。确保query_logic的代码和API真实存在可以正确执行。尽量使用简单的代码来做查询, 比如, 如果想要确认某东西是否存在, 直接让返回结果为true或false。如果想要获取某个东西的值, 直接让返回结果为该值, 但是注意该值会被JSON.stringify, 所以不要返回对象, 而是返回字符串。"
                }
            },
            required: ["execute_logic", "query_logic"]
        }
    }
};

export type ToolFunction = (args: any) => Promise<any>;

export const toolImplementations: Record<string, ToolFunction> = {
    "api-doc-search": async ({ keyword }: { keyword: string }) => {
        const encodedTopic = encodeURIComponent(keyword);
        const url = `https://context7.com/api/v1/llmstxt/developer_mescius_com-spreadjs-docs-llms.txt?type=json&tokens=100000&topic=${encodedTopic}`;

        const res = await fetch(url, {
            method: "GET",
            headers: {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                "content-type": "application/json",
            },
            mode: "cors",
            credentials: "omit"
        });

        const data = await res.json();

        // Context7返回格式：{ snippets: [...] }
        if (data && data.snippets && Array.isArray(data.snippets)) {
            return data.snippets.slice(0, 8).map((snippet: any, index: number) => {
                let content = `**${snippet.codeTitle || '代码示例'}**\n\n`;

                if (snippet.codeDescription) {
                    content += `描述: ${snippet.codeDescription}\n\n`;
                }

                if (snippet.pageTitle) {
                    content += `来源: ${snippet.pageTitle}\n\n`;
                }

                // 添加代码示例
                if (snippet.codeList && snippet.codeList.length > 0) {
                    content += `代码示例:\n\`\`\`${snippet.codeLanguage || 'javascript'}\n`;
                    content += snippet.codeList[0].code || '';
                    content += '\n```';
                }

                return {
                    id: index + 1,
                    title: snippet.codeTitle || `示例 ${index + 1}`,
                    description: snippet.codeDescription || '',
                    content: content,
                    code: snippet.codeList?.[0]?.code || '',
                    source: snippet.pageTitle || 'SpreadJS Documentation',
                    relevance: snippet.relevance || 0,
                    url: snippet.codeId || ''
                };
            });
        }

        // 如果格式不符合预期，返回错误信息
        console.error('Context7 unexpected response format:', data);
        return [{
            id: 1,
            content: `Context7搜索返回格式异常，关键词: ${keyword}`,
            source: 'Context7 Error',
            error: true
        }];
    },

    "execute-spreadjs": async ({ execute_logic, query_logic }: { execute_logic: string; query_logic: string }) => {
        console.log(`[Tool Call: execute-SpreadJS] Generating code...`);

        // 返回代码给前端执行
        const responseToFrontend = JSON.stringify({
            execute: execute_logic,
            query: query_logic,
        });

        console.log(`[Tool Result: execute-SpreadJS] Code generated for frontend.`);
        return responseToFrontend;
    }
};
